﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Xml.Linq;
using Blue.ResourceManager;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using Green.Logging;

namespace EngineOfEvermore.Scene.Physics
{
    class CollisionGroupSetup : Resource
    {
        #region Constants
        static readonly XNamespace ENGINE_OF_EVERMORE_NAMESPACE = 
            "http://engineofevermore.wordpress.com/EngineOfEvermore.xsd"; 

        static readonly XName COLLISION_GROUPS_TAG_NAME = 
            ENGINE_OF_EVERMORE_NAMESPACE + "CollisionGroups";

        static readonly XName COLLISION_GROUP_TAG_NAME = 
            ENGINE_OF_EVERMORE_NAMESPACE + "Group";

        static readonly XName COLLISION_SETUP_TAG_NAME = 
            ENGINE_OF_EVERMORE_NAMESPACE + "CollisionSetup";

        static readonly XName GROUP_PAIR_ATTRIBUTE_NAME_1 = "group1";
        static readonly XName GROUP_PAIR_ATTRIBUTE_NAME_2 = "group2";
        #endregion

        #region struct MaskPair
        struct MaskPair
        {
            public ushort CategoryBits;
            public ushort MaskBits;
        }
        #endregion

        #region Variables
        HashSet<String> _groups = new HashSet<String>();
        Dictionary<String, MaskPair> _masks = new Dictionary<String, MaskPair>();
        #endregion

        #region Properties
        public IEnumerable<String> CollisionGroups
        {
            get { return _groups; }
        }
        #endregion

        #region Constructor (Private)
        CollisionGroupSetup( String resourceName ):
            base( resourceName )
        {
        }
        #endregion

        #region Public Methods
        public void GetMasksForGroup( String group, out ushort maskBits, out ushort categoryBits )
        {
            MaskPair maskPair = _masks[group];

            categoryBits = maskPair.CategoryBits;
            maskBits = maskPair.MaskBits;
        }

        public bool ContainsGroup( String group )
        {
            return _groups.Contains( group );
        }

        public static CollisionGroupSetup LoadFromStream( String resourceName, Stream stream )
        {
            CollisionGroupSetup res = new CollisionGroupSetup( resourceName );

            if ( _readerSettings == null )
            {
                _createXmlReaderSettings();
            }

            XmlReader xmlReader = XmlReader.Create( stream, _readerSettings );
            XDocument xdoc = XDocument.Load( xmlReader );
            res._buildMasks( xdoc );

            return res;
        }
        #endregion

        #region Private Methods
        void _buildMasks( XDocument xdoc )
        {
            Dictionary<String, int> indices = new Dictionary<String, int>();

            XElement groupsElement = xdoc.Root.Element( COLLISION_GROUPS_TAG_NAME );

            int groupCount = 0;
            foreach ( XElement groupElement in groupsElement.Elements() )
            {
                String groupName = (String) groupElement;
                MaskPair maskPair = new MaskPair();
                maskPair.CategoryBits = (ushort)( 1 << groupCount );
                _masks[groupName] = maskPair;
                _groups.Add( groupName );

                groupCount++;
            }

            XElement setupElement = xdoc.Root.Elements( COLLISION_SETUP_TAG_NAME ).Single();

            foreach ( XElement pairElement in setupElement.Elements() )
            {
                String group1Name = pairElement.Attribute( GROUP_PAIR_ATTRIBUTE_NAME_1 ).Value;
                String group2Name = pairElement.Attribute( GROUP_PAIR_ATTRIBUTE_NAME_2 ).Value;

                MaskPair maskPair1 = _masks[group1Name];
                MaskPair maskPair2 = _masks[group2Name];

                maskPair1.MaskBits |= maskPair2.CategoryBits;
                maskPair2.MaskBits |= maskPair1.CategoryBits;

                _masks[group1Name] = maskPair1;
                _masks[group2Name] = maskPair2;
            }
        }

        const String XML_SCHEMA_LOCATION_RESOURCE_NAME = 
            "XmlSchema/EngineOfEvermore.CollisionGroupSetup.xsd";
        static XmlReaderSettings _readerSettings;

        static void _createXmlReaderSettings()
        {
            if ( _readerSettings == null )
            {
                XmlSchema schema = null;

                using ( Stream schemaStream = ResourceManager.OpenStream(
                    XML_SCHEMA_LOCATION_RESOURCE_NAME,
                    ResourceOpenMode.Read
                    ) )
                {
                    schema = XmlSchema.Read( schemaStream, _schemaLoadMessageHandler );
                }

                _readerSettings = new XmlReaderSettings();
                _readerSettings.CheckCharacters = true;
                _readerSettings.CloseInput = false;
                _readerSettings.IgnoreComments = true;
                _readerSettings.IgnoreProcessingInstructions = true;
                _readerSettings.IgnoreWhitespace = true;
                _readerSettings.Schemas = new XmlSchemaSet();
                _readerSettings.Schemas.Add( schema );
                _readerSettings.ValidationFlags = 
                    XmlSchemaValidationFlags.ReportValidationWarnings;
                _readerSettings.ValidationType = ValidationType.Schema;
            }
        }

        static void _schemaLoadMessageHandler( object sender, ValidationEventArgs e )
        {
            switch ( e.Severity )
            { 
                case XmlSeverityType.Warning:
                    Log.Warning( "Error loading CollisionGroupSetup schema file: " + e.Message );
                    break;

                case XmlSeverityType.Error:
                    Log.Error( "Error loading CollisionGroupSetup schema file: " + e.Message );
                    break;
            }
        }

        static void _xmlLoadMessageHandler( object sender, ValidationEventArgs e )
        {
            switch ( e.Severity )
            {
                case XmlSeverityType.Warning:
                    Log.Warning( "Error loading CollisionGroupSetup definition file: " + 
                        e.Message );
                    break;

                case XmlSeverityType.Error:
                    Log.Error( "Error loading CollisionGroupSetup definition file: " + e.Message );
                    break;
            }
        }
        #endregion
    }
}
